<template>
  <el-dialog
    title="参数设置"
    :visible.sync="dialogVisible"
    width="1000px"
  >
    <el-empty v-if="tableData.length === 0" description="暂无任何计算结果">
      <file-upload :action="uploadUrl" :name="name" @onSuccess="onSuccess" />
    </el-empty>
    <div v-else>
      <el-table
        border
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="lng"
          label="经度"
          align="center"
        />
        <el-table-column
          prop="lat"
          label="纬度"
          align="center"
        />
        <el-table-column
          prop="residual_water_content"
          label="田间持水量"
          align="center"
        />
        <el-table-column
          prop="saturated_water_content"
          label="凋萎含水率"
          align="center"
        />
        <el-table-column
          prop="awc"
          label="土壤可利用水量"
          align="center"
        />
      </el-table>
      <div class="h12" />
      <div>
        <el-button type="primary" @click="reCompute">重新计算</el-button>
        <el-button type="success" @click="addLayer">插值并保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import * as turf from '@turf/turf'
import { mapGetters } from 'vuex'
import { colors } from '@/utils/constant'
export default {
  components: {
    FileUpload
  },
  data() {
    return {
      tableData: [],
      uploadUrl: 'https://api.zesi.com.cn/idata/util/upload',
      name: 'awc',
      grid: [],
      colors,
      dialogVisible: false
    }
  },
  computed: {
    ...mapGetters(['project']),
    circlePolygon() {
      const center = [this.project.lng, this.project.lat]
      const radius = 0.1499
      const options = { steps: 100, units: 'kilometers', properties: { foo: 'bar' }}
      return turf.circle(center, radius, options)
    }
  },
  methods: {
    show() {
      this.dialogVisible = true
    },
    reCompute() {
      this.tableData = []
    },
    onSuccess(response, file) {
      const { errorCode, msg, data } = response
      if (errorCode !== 0) {
        this.$message({
          message: (msg && `上传失败，失败原因：${msg}`) || '上传失败',
          type: 'error'
        })
        this.$emit('onError', data)
      } else {
        this.$message({
          message: '上传成功',
          type: 'success'
        })
        this.tableData = data
      }
    },
    addLayer() {
      const data = this.tableData
      var features = data.map(i => {
        return {
          type: 'Feature',
          properties: {
            value: i.awc
          },
          geometry: {
            type: 'Point',
            coordinates: [+i.lng, +i.lat]
          }
        }
      }
      )

      var points = turf.featureCollection(features)
      var interpolate_options = {
        gridType: 'points',
        property: 'value',
        units: 'degrees',
        weight: 10
      }

      console.log(points)

      var grid = turf.interpolate(points, 0.0001, interpolate_options)

      console.log(grid)

      // 适当降低插值结果的精度便于显示
      // grid.features.map((i) => (i.properties.value = i.properties.value.toFixed(5)))

      this.grid = grid.features.map((val) => {
        return {
          lat: val.geometry.coordinates[1],
          lng: val.geometry.coordinates[0],
          awc: val.properties.value
        }
      })

      var isobands_options = {
        zProperty: 'value',
        commonProperties: {
          'fill-opacity': 1
        },
        breaksProperties: colors.map(val => {
          return { fill: val.color }
        })
      }

      console.log(grid)

      let isobands = turf.isobands(
        grid,
        [1, 192.65, 195.40, 197.24, 200.20, 500],
        isobands_options
      )
      console.log(isobands)
      isobands = turf.flatten(isobands)

      console.log(isobands)

      const features_filter = []
      isobands.features.forEach((layer) => {
        let intersection = null
        try {
          intersection = turf.intersect(layer, this.circlePolygon)
        } catch (e) {
          layer = turf.buffer(layer, 0)
          intersection = turf.intersect(layer, this.circlePolygon)
        }
        if (intersection != null) {
          intersection.properties = layer.properties
          features_filter.push(intersection)
        }
      })
      isobands.features = features_filter

      const geoArr = isobands
      // eslint-disable-next-line no-undef
      const res = L.geoJson(geoArr, { style: this.getFlexStyle })

      this.dialogVisible = false
      this.tableData = []
      this.$emit('addLayer', res, data)
    },
    getFlexStyle(feature) {
      return {
        weight: 1,
        opacity: 0,
        color: '#fff',
        fillOpacity: 0.6,
        fillColor: feature.properties.fill }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
